import DetectorModal from '@/components/DetectorManage/detectorModal';
import DetectorPushEmial from '@/components/DetectorManage/detectorPushEmial';
import FormFilter from '@/components/ManageFormFilter/FormFilter';
import {
  DeleteOutlined,
  PlusCircleOutlined,
  RedoOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper, recordKeyToString } from '@ant-design/pro-components';
import { Badge, Button, Card, Col, Form, Input, Popconfirm, Row, Table, Tag, message } from 'antd';
import React, { Component } from 'react';
import { connect } from 'umi';

class DetectorManager extends Component {
  componentDidMount() {
    // 当页面组件完全的加载完毕触发此生命周期，只会触发一次
    this.formRef = React.createRef();
    this.modalRef = React.createRef();
    this.tableRef = React.createRef();
    //初始数据加载
    this.handleRefreshData();
  }

  //请求设备器table表数据
  handleRefreshData() {
    let formData = {};
    try {
      const getFormData = this.formRef.current.getFieldsValue();
      formData = { ...getFormData };
    } catch (e) {
      formData = undefined;
    }

    // 获取表格数据
    const { dispatch } = this.props;

    dispatch({
      type: 'detectorManage/changeLoadingStatus',
    });
    if (dispatch) {
      dispatch({
        type: 'detectorManage/getData',
        payload: formData ? { formData } : {},
      });
    }
  }
  //重置查询表单
  resetAllFields() {
    const { current } = this.formRef;
    current.resetFields();
  }

  //新增/修改Model
  changeModal(type = 'add', data = {}) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'detectorManage/changeModalVisibleAndSetValue',
        payload:
          type === 'update'
            ? {
              type,
              data,
            }
            : {
              type,
            },
      });
  }

  changePage(currentPage) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'detectorManage/changePage',
        payload: currentPage,
      }).then(() => {
        this.handleRefreshData();
      });
  }

  submitDetectorInfo(type = 'add', values) {
    const { dispatch } = this.props;

    let { producedDate } = values;
    producedDate = values.producedDate.format('YYYY-MM-DD HH:mm:ss');

    dispatch &&
      dispatch({
        type: 'detectorManage/submitDetectorInfo',
        payload: {
          type,
          formData: {
            ...values,
            producedDate,
            // devAddress: values.devAddress.join('/'),
          },
        },
        callback: (res) => {
          if (res.code == 200) {
            message.success(`${type === 'add' ? '添加' : '修改'}成功`);
            this.handleCancel();
            this.handleRefreshData(); // 刷新列表
          } else {
            message.error(res.message);
          }
        },
      });
  }

  //关闭modal窗
  handleCancel() {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'detectorManage/changeModelVisibleAndCloseModel',
      });
  }

  //改变Drawer状态并保存行记录
  changeDrawerStatusAndSaveRecord(record) {
    const { dispatch } = this.props;
    dispatch &&
      dispatch({
        type: 'detectorManage/changeDrawerStatus',
        payload: record,
      });
  }

  //删除设备根据id
  deleteDetectorById(record) {
    const { dispatch } = this.props;
    //删除用户
    dispatch &&
      dispatch({
        type: 'detectorManage/deleteDetectorInfo',
        payload: record,
        callback: (res) => {
          if (res.code == 200) {
            message.success(`删除成功`);
            this.handleRefreshData(); // 刷新列表
          } else {
            message.error(res.message);
          }
        },
      });
  }

  render() {
    const {
      detectors,
      loading,
      selectedRowsKeys = [],
      dispatch,
      modalVisible,
      drawerVisible,
      optiontype,
      detectorDetail,
      effectPageInfo,
      pagination,
    } = this.props;
    const formName = '监测设备条件搜索';
    const tableName = '设备列表';
    const columns = [
      {
        title: '序号',
        dataIndex: 'id',
        showFilter: false,
        align: 'center',
        render: (value, record, index) => {
          return `${(effectPageInfo.current - 1) * pagination.size + index + 1}`;
        },
      },
      {
        title: '断面名称(编号)',
        dataIndex: 'deviceId',
        showFilter: true,
        align: 'center',
      },
      {
        title: '设备名称',
        dataIndex: 'deviceName',
        showFilter: true,
        align: 'center',
      },
      {
        title: '设备型号',
        dataIndex: 'unitType',
        showFilter: true,
        align: 'center',
        render: (value, record) => {
          {
            return <Tag color="purple">{value}</Tag>;
          }
        },
      },
      {
        title: '所在位置',
        dataIndex: 'devAddress',
        showFilter: false,
        align: 'center',
      },
      {
        title: '运行状态',
        dataIndex: 'status',
        showFilter: true,
        checkbox: true,
        defaultValue: ['0', '1', '2'],
        align: 'center',
        Option: [
          { value: '0', label: '正常' },
          { value: '1', label: '损坏' },
          { value: '2', label: '停用' },
        ],
        render: (value, record) => {
          switch (value) {
            case '0':
              return (
                <Badge status={'processing'} text={<b style={{ color: '#2396ff' }}>正常</b>} />
              );
            case '1':
              return <Badge status={'warning'} text={<b style={{ color: '#faad14' }}>损坏</b>} />;
            case '2':
              return <Badge status={'error'} text={<b style={{ color: 'red' }}>停用</b>} />;
          }
        },
      },
      {
        title: '使用年限',
        dataIndex: 'durableYear',
        key: 'roleName',
        align: 'center',
      },
      {
        title: '出厂日期',
        dataIndex: 'producedDate',
        key: 'devAddress',
        align: 'center',
      },

      {
        title: '操作',
        dataIndex: '',
        width: 250,
        align: 'center',
        render: (text, record, index) => {
          return (
            <div>
              <Button
                type={'primary'}
                size={'small'}
                style={{ marginRight: 5 }}
                onClick={() => {
                  this.changeModal('update', record);
                }}
              >
                修改
              </Button>
              <Popconfirm
                title="确定删除此设备?"
                onConfirm={() => {
                  this.deleteDetectorById(record);
                }}
              >
                <Button type={'primary'} danger size={'small'}>
                  删除
                </Button>
              </Popconfirm>
            </div>
          );
        },
      },
    ];
    return (
      <PageHeaderWrapper>
        <Row>
          <Col span={24}>
            <Card title={formName} bordered={false} style={{ marginBottom: 20 }}>
              <Row>
                <Form
                  layout="inline"
                  ref={this.formRef}
                  onFinish={(values) => {
                    this.handleRefreshData();
                  }}
                  style={{ marginBottom: 20 }}
                >
                  <FormFilter columns={columns} />
                  <Button
                    type="primary"
                    htmlType="submit"
                    style={{ marginRight: 20, marginTop: 8 }}
                  >
                    <SearchOutlined />
                    查询
                  </Button>
                  <Button
                    type="primary"
                    htmlType="button"
                    style={{ marginTop: 8 }}
                    onClick={() => {
                      this.resetAllFields();
                    }}
                  >
                    <RedoOutlined /> 重置
                  </Button>
                </Form>
              </Row>
              <Row>
                <Button
                  type="primary"
                  htmlType="button"
                  style={{ marginRight: 20 }}
                  onClick={() => {
                    this.changeModal();
                  }}
                >
                  <PlusCircleOutlined />
                  新增监测器设备
                </Button>
                <Button type="primary" htmlType="button" danger>
                  <DeleteOutlined /> 批量删除
                </Button>
              </Row>
            </Card>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Card bordered={false}>
              <Table
                rowKey={'id'}
                dataSource={detectors}
                loading={loading}
                columns={columns}
                ref={this.tableRef}
                scroll={{ x: 'max-content' }}
                size={'small'}
                pagination={{
                  showQuickJumper: false,
                  showTotal: () => `共${pagination.total}条`,
                  pageSize: pagination.size,
                  total: pagination.total, //数据的总的条数
                  onChange: (current) => this.changePage(current), //点击当前页码
                }}
              />
            </Card>
          </Col>
        </Row>

        <DetectorModal
          visible={modalVisible}
          optiontype={optiontype}
          detectorDetail={detectorDetail}
          ref={this.modalRef}
          handleSumbit={(type, values) => {
            this.submitDetectorInfo(type, values);
          }}
          centered
        />

        <DetectorPushEmial handleRefreshData={() => this.handleRefreshData()} />
      </PageHeaderWrapper>
    );
  }
}

export default connect(({ detectorManage }) => ({
  detectors: detectorManage.detectors,
  loading: detectorManage.loading,
  pagination: detectorManage.pagination,
  selectedRowsKeys: detectorManage.selectedRowsKeys,
  modalVisible: detectorManage.modalVisible,
  drawerVisible: detectorManage.drawerVisible,
  optiontype: detectorManage.optiontype,
  effectPageInfo: detectorManage.effectPageInfo,
  detectorDetail: detectorManage.detectorDetail,
}))(DetectorManager);
